import 'package:get/get.dart';
import 'package:flutter/material.dart';
import '../data/models/app_settings.dart';
import '../data/repositories/settings_repository.dart';
import '../data/repositories/settings_repository_impl.dart';
import '../data/services/database_service.dart';

/// 设置控制器
/// Settings controller
class SettingsController extends GetxController {
  final SettingsRepository _settingsRepository = SettingsRepositoryImpl();
  final DatabaseService _databaseService = DatabaseService();

  // 响应式状态变量
  // Reactive state variables
  final Rx<AppThemeMode> _themeMode = AppThemeMode.system.obs;
  final RxBool _notificationsEnabled = true.obs;
  final Rx<FontSize> _fontSize = FontSize.medium.obs;
  final RxBool _isFirstLaunch = true.obs;
  final RxString _language = 'zh_CN'.obs;
  final RxBool _autoBackupEnabled = false.obs;
  final Rx<ReminderFrequency> _reminderFrequency = ReminderFrequency.daily.obs;
  final RxBool _isLoading = false.obs;
  final RxString _errorMessage = ''.obs;
  final RxString _appVersion = '1.0.0'.obs;
  final RxString _databasePath = ''.obs;
  final RxDouble _databaseSize = 0.0.obs;
  final RxInt _totalRecords = 0.obs;
  final RxBool _biometricEnabled = false.obs;
  final RxBool _analyticsEnabled = true.obs;
  final RxBool _crashReportingEnabled = true.obs;
  final Rx<TimeOfDay> _reminderTime = TimeOfDay.now().obs;
  final Rx<BackupFrequency> _backupFrequency = BackupFrequency.weekly.obs;
  final Rx<LockType> _lockType = LockType.none.obs;
  final RxInt _autoLockTime = 5.obs; // minutes

  /// 应用锁定是否启用
  /// App lock enabled
  final RxBool _appLockEnabled = false.obs;

  /// 数据加密是否启用
  /// Data encryption enabled
  final _dataEncryptionEnabled = false.obs;

  /// 每日提醒是否启用
  /// Daily reminder enabled
  final _dailyReminderEnabled = true.obs;

  /// 周末提醒是否启用
  /// Weekend reminder enabled
  final _weekendReminderEnabled = false.obs;

  // Getters for accessing reactive state
  AppThemeMode get themeMode => _themeMode.value;
  bool get notificationsEnabled => _notificationsEnabled.value;
  FontSize get fontSize => _fontSize.value;
  bool get isFirstLaunch => _isFirstLaunch.value;
  String get language => _language.value;
  bool get autoBackupEnabled => _autoBackupEnabled.value;
  ReminderFrequency get reminderFrequency => _reminderFrequency.value;
  bool get isLoading => _isLoading.value;
  String get errorMessage => _errorMessage.value;
  String get appVersion => _appVersion.value;
  String get databasePath => _databasePath.value;
  double get databaseSize => _databaseSize.value;
  int get totalRecords => _totalRecords.value;
  bool get biometricEnabled => _biometricEnabled.value;
  bool get analyticsEnabled => _analyticsEnabled.value;
  bool get crashReportingEnabled => _crashReportingEnabled.value;
  TimeOfDay get reminderTime => _reminderTime.value;
  BackupFrequency get backupFrequency => _backupFrequency.value;
  LockType get lockType => _lockType.value;
  int get autoLockTime => _autoLockTime.value;
  bool get appLockEnabled => _appLockEnabled.value;
  bool get dataEncryptionEnabled => _dataEncryptionEnabled.value;
  bool get dailyReminderEnabled => _dailyReminderEnabled.value;
  bool get weekendReminderEnabled => _weekendReminderEnabled.value;

  @override
  void onInit() {
    super.onInit();
    // 初始化时加载设置
    // Load settings on initialization
    loadAllSettings();
    loadAppInfo();
  }

  /// 加载所有设置
  /// Load all settings
  Future<void> loadAllSettings() async {
    try {
      _isLoading.value = true;
      _errorMessage.value = '';
      
      // 加载各项设置
      // Load individual settings
      await Future.wait([
        _loadThemeMode(),
        _loadNotificationsEnabled(),
        _loadFontSize(),
        _loadIsFirstLaunch(),
        _loadLanguage(),
        _loadAutoBackupEnabled(),
        _loadReminderFrequency(),
        _loadBiometricEnabled(),
        _loadAnalyticsEnabled(),
        _loadCrashReportingEnabled(),
      ]);
    } catch (e) {
      _errorMessage.value = '加载设置失败: ${e.toString()}';
      Get.snackbar('错误', '加载设置失败', snackPosition: SnackPosition.BOTTOM);
    } finally {
      _isLoading.value = false;
    }
  }

  /// 加载应用信息
  /// Load app information
  Future<void> loadAppInfo() async {
    try {
      // 获取数据库路径和大小
      // Get database path and size
      final dbPath = await _databaseService.getDatabasePath();
      final dbSize = await _databaseService.getDatabaseSize();
      
      _databasePath.value = dbPath;
      _databaseSize.value = dbSize.toDouble();
      
      // 这里可以添加获取记录总数的逻辑
      // Logic to get total records count can be added here
      // _totalRecords.value = await _emotionRepository.getRecordCount();
    } catch (e) {
      print('加载应用信息失败: $e');
    }
  }

  /// 加载主题模式
  /// Load theme mode
  Future<void> _loadThemeMode() async {
    final themeMode = await _settingsRepository.getThemeMode();
    _themeMode.value = themeMode;
  }

  /// 加载通知设置
  /// Load notification settings
  Future<void> _loadNotificationsEnabled() async {
    final enabled = await _settingsRepository.getNotificationsEnabled();
    _notificationsEnabled.value = enabled;
  }

  /// 加载字体大小
  /// Load font size
  Future<void> _loadFontSize() async {
    final fontSize = await _settingsRepository.getFontSize();
    _fontSize.value = fontSize;
  }

  /// 加载首次启动标志
  /// Load first launch flag
  Future<void> _loadIsFirstLaunch() async {
    final isFirst = await _settingsRepository.getIsFirstLaunch();
    _isFirstLaunch.value = isFirst;
  }

  /// 加载语言设置
  /// Load language setting
  Future<void> _loadLanguage() async {
    final language = await _settingsRepository.getLanguage();
    _language.value = language;
  }

  /// 加载自动备份设置
  /// Load auto backup setting
  Future<void> _loadAutoBackupEnabled() async {
    final enabled = await _settingsRepository.getAutoBackupEnabled();
    _autoBackupEnabled.value = enabled;
  }

  /// 加载提醒频率
  /// Load reminder frequency
  Future<void> _loadReminderFrequency() async {
    final frequency = await _settingsRepository.getReminderFrequency();
    _reminderFrequency.value = frequency;
  }

  /// 加载生物识别设置
  /// Load biometric setting
  Future<void> _loadBiometricEnabled() async {
    final enabled = await _settingsRepository.getSetting(SettingsKeys.biometricEnabled) == 'true';
    _biometricEnabled.value = enabled;
  }

  /// 加载分析数据设置
  /// Load analytics setting
  Future<void> _loadAnalyticsEnabled() async {
    final enabled = await _settingsRepository.getSetting(SettingsKeys.analyticsEnabled) == 'true';
    _analyticsEnabled.value = enabled;
  }

  /// 加载崩溃报告设置
  /// Load crash reporting setting
  Future<void> _loadCrashReportingEnabled() async {
    final enabled = await _settingsRepository.getSetting(SettingsKeys.crashReportingEnabled) == 'true';
    _crashReportingEnabled.value = enabled;
  }

  /// 设置主题模式
  /// Set theme mode
  Future<void> setThemeMode(AppThemeMode mode) async {
    try {
      await _settingsRepository.setThemeMode(mode);
      _themeMode.value = mode;
      
      // 应用主题变化
      // Apply theme change
      _applyThemeMode(mode);
      
      Get.snackbar('成功', '主题已更新', snackPosition: SnackPosition.BOTTOM);
    } catch (e) {
      _errorMessage.value = '设置主题失败: ${e.toString()}';
      Get.snackbar('错误', '设置主题失败', snackPosition: SnackPosition.BOTTOM);
    }
  }

  /// 应用主题模式
  /// Apply theme mode
  void _applyThemeMode(AppThemeMode mode) {
    switch (mode) {
      case AppThemeMode.light:
        Get.changeThemeMode(ThemeMode.light);
        break;
      case AppThemeMode.dark:
        Get.changeThemeMode(ThemeMode.dark);
        break;
      case AppThemeMode.system:
        Get.changeThemeMode(ThemeMode.system);
        break;
    }
  }

  /// 设置通知开关
  /// Set notifications enabled
  Future<void> setNotificationsEnabled(bool enabled) async {
    try {
      await _settingsRepository.setNotificationsEnabled(enabled);
      _notificationsEnabled.value = enabled;
      
      Get.snackbar(
        '成功', 
        enabled ? '通知已开启' : '通知已关闭', 
        snackPosition: SnackPosition.BOTTOM,
      );
    } catch (e) {
      _errorMessage.value = '设置通知失败: ${e.toString()}';
      Get.snackbar('错误', '设置通知失败', snackPosition: SnackPosition.BOTTOM);
    }
  }

  /// 设置字体大小
  /// Set font size
  Future<void> setFontSize(FontSize size) async {
    try {
      await _settingsRepository.setFontSize(size);
      _fontSize.value = size;
      
      Get.snackbar('成功', '字体大小已更新', snackPosition: SnackPosition.BOTTOM);
    } catch (e) {
      _errorMessage.value = '设置字体大小失败: ${e.toString()}';
      Get.snackbar('错误', '设置字体大小失败', snackPosition: SnackPosition.BOTTOM);
    }
  }

  /// 设置语言
  /// Set language
  Future<void> setLanguage(String languageCode) async {
    try {
      await _settingsRepository.setLanguage(languageCode);
      _language.value = languageCode;
      
      // 应用语言变化
      // Apply language change
      _applyLanguage(languageCode);
      
      Get.snackbar('成功', '语言已更新', snackPosition: SnackPosition.BOTTOM);
    } catch (e) {
      _errorMessage.value = '设置语言失败: ${e.toString()}';
      Get.snackbar('错误', '设置语言失败', snackPosition: SnackPosition.BOTTOM);
    }
  }

  /// 应用语言设置
  /// Apply language setting
  void _applyLanguage(String languageCode) {
    final parts = languageCode.split('_');
    if (parts.length == 2) {
      final locale = Locale(parts[0], parts[1]);
      Get.updateLocale(locale);
    }
  }

  /// 设置自动备份
  /// Set auto backup
  Future<void> setAutoBackupEnabled(bool enabled) async {
    try {
      await _settingsRepository.setAutoBackupEnabled(enabled);
      _autoBackupEnabled.value = enabled;
      
      Get.snackbar(
        '成功', 
        enabled ? '自动备份已开启' : '自动备份已关闭', 
        snackPosition: SnackPosition.BOTTOM,
      );
    } catch (e) {
      _errorMessage.value = '设置自动备份失败: ${e.toString()}';
      Get.snackbar('错误', '设置自动备份失败', snackPosition: SnackPosition.BOTTOM);
    }
  }

  /// 设置提醒频率
  /// Set reminder frequency
  Future<void> setReminderFrequency(ReminderFrequency frequency) async {
    try {
      await _settingsRepository.setReminderFrequency(frequency);
      _reminderFrequency.value = frequency;
      
      Get.snackbar('成功', '提醒频率已更新', snackPosition: SnackPosition.BOTTOM);
    } catch (e) {
      _errorMessage.value = '设置提醒频率失败: ${e.toString()}';
      Get.snackbar('错误', '设置提醒频率失败', snackPosition: SnackPosition.BOTTOM);
    }
  }

  /// 设置提醒时间
  /// Set reminder time
  Future<void> setReminderTime(TimeOfDay time) async {
    try {
      _reminderTime.value = time;
      Get.snackbar('成功', '提醒时间已更新', snackPosition: SnackPosition.BOTTOM);
    } catch (e) {
      _errorMessage.value = '设置提醒时间失败: ${e.toString()}';
      Get.snackbar('错误', '设置提醒时间失败', snackPosition: SnackPosition.BOTTOM);
    }
  }

  /// 设置备份频率
  /// Set backup frequency
  Future<void> setBackupFrequency(BackupFrequency frequency) async {
    try {
      _backupFrequency.value = frequency;
      Get.snackbar('成功', '备份频率已更新', snackPosition: SnackPosition.BOTTOM);
    } catch (e) {
      _errorMessage.value = '设置备份频率失败: ${e.toString()}';
      Get.snackbar('错误', '设置备份频率失败', snackPosition: SnackPosition.BOTTOM);
    }
  }

  /// 设置锁定类型
  /// Set lock type
  Future<void> setLockType(LockType type) async {
    try {
      _lockType.value = type;
      Get.snackbar('成功', '锁定类型已更新', snackPosition: SnackPosition.BOTTOM);
    } catch (e) {
      _errorMessage.value = '设置锁定类型失败: ${e.toString()}';
      Get.snackbar('错误', '设置锁定类型失败', snackPosition: SnackPosition.BOTTOM);
    }
  }

  /// 设置自动锁定时间
  /// Set auto lock time
  Future<void> setAutoLockTime(int minutes) async {
    try {
      _autoLockTime.value = minutes;
      Get.snackbar('成功', '自动锁定时间已更新', snackPosition: SnackPosition.BOTTOM);
    } catch (e) {
      _errorMessage.value = '设置自动锁定时间失败: ${e.toString()}';
      Get.snackbar('错误', '设置自动锁定时间失败', snackPosition: SnackPosition.BOTTOM);
    }
  }

  /// 设置生物识别
  /// Set biometric enabled
  Future<void> setBiometricEnabled(bool enabled) async {
    try {
      await _settingsRepository.setSetting(
        SettingsKeys.biometricEnabled, 
        enabled.toString(),
      );
      _biometricEnabled.value = enabled;
      
      Get.snackbar(
        '成功', 
        enabled ? '生物识别已开启' : '生物识别已关闭', 
        snackPosition: SnackPosition.BOTTOM,
      );
    } catch (e) {
      _errorMessage.value = '设置生物识别失败: ${e.toString()}';
      Get.snackbar('错误', '设置生物识别失败', snackPosition: SnackPosition.BOTTOM);
    }
  }

  /// 设置分析数据收集
  /// Set analytics enabled
  Future<void> setAnalyticsEnabled(bool enabled) async {
    try {
      await _settingsRepository.setSetting(
        SettingsKeys.analyticsEnabled, 
        enabled.toString(),
      );
      _analyticsEnabled.value = enabled;
      
      Get.snackbar(
        '成功', 
        enabled ? '数据分析已开启' : '数据分析已关闭', 
        snackPosition: SnackPosition.BOTTOM,
      );
    } catch (e) {
      _errorMessage.value = '设置数据分析失败: ${e.toString()}';
      Get.snackbar('错误', '设置数据分析失败', snackPosition: SnackPosition.BOTTOM);
    }
  }

  /// 设置崩溃报告
  /// Set crash reporting enabled
  Future<void> setCrashReportingEnabled(bool enabled) async {
    try {
      await _settingsRepository.setSetting(
        SettingsKeys.crashReportingEnabled, 
        enabled.toString(),
      );
      _crashReportingEnabled.value = enabled;
      
      Get.snackbar(
        '成功', 
        enabled ? '崩溃报告已开启' : '崩溃报告已关闭', 
        snackPosition: SnackPosition.BOTTOM,
      );
    } catch (e) {
      _errorMessage.value = '设置崩溃报告失败: ${e.toString()}';
      Get.snackbar('错误', '设置崩溃报告失败', snackPosition: SnackPosition.BOTTOM);
    }
  }

  /// 标记首次启动完成
  /// Mark first launch completed
  Future<void> markFirstLaunchCompleted() async {
    try {
      await _settingsRepository.setIsFirstLaunch(false);
      _isFirstLaunch.value = false;
    } catch (e) {
      print('标记首次启动完成失败: $e');
    }
  }

  /// 重置所有设置
  /// Reset all settings
  Future<void> resetAllSettings() async {
    try {
      _isLoading.value = true;
      
      await _settingsRepository.resetToDefaults();
      await loadAllSettings();
      
      Get.snackbar('成功', '设置已重置为默认值', snackPosition: SnackPosition.BOTTOM);
    } catch (e) {
      _errorMessage.value = '重置设置失败: ${e.toString()}';
      Get.snackbar('错误', '重置设置失败', snackPosition: SnackPosition.BOTTOM);
    } finally {
      _isLoading.value = false;
    }
  }

  /// 备份数据库
  /// Backup database
  Future<void> backupDatabase() async {
    try {
      _isLoading.value = true;
      
      final backupPath = await _databaseService.backupDatabase();
      
      Get.snackbar(
        '成功', 
        '数据库已备份到: $backupPath', 
        snackPosition: SnackPosition.BOTTOM,
        duration: const Duration(seconds: 5),
      );
    } catch (e) {
      _errorMessage.value = '备份数据库失败: ${e.toString()}';
      Get.snackbar('错误', '备份数据库失败', snackPosition: SnackPosition.BOTTOM);
    } finally {
      _isLoading.value = false;
    }
  }

  /// 恢复数据库
  /// Restore database
  Future<void> restoreDatabase(String backupPath) async {
    try {
      _isLoading.value = true;
      
      await _databaseService.restoreDatabase(backupPath);
      
      Get.snackbar(
        '成功', 
        '数据库已从备份恢复', 
        snackPosition: SnackPosition.BOTTOM,
      );
    } catch (e) {
      _errorMessage.value = '恢复数据库失败: ${e.toString()}';
      Get.snackbar('错误', '恢复数据库失败', snackPosition: SnackPosition.BOTTOM);
    } finally {
      _isLoading.value = false;
    }
  }

  /// 清除所有数据
  /// Clear all data
  Future<void> clearAllData() async {
    try {
      _isLoading.value = true;
      
      // 显示确认对话框
      // Show confirmation dialog
      final confirmed = await Get.dialog<bool>(
        AlertDialog(
          title: const Text('确认清除'),
          content: const Text('此操作将删除所有情绪记录和媒体文件，且无法恢复。确定要继续吗？'),
          actions: [
            TextButton(
              onPressed: () => Get.back(result: false),
              child: const Text('取消'),
            ),
            TextButton(
              onPressed: () => Get.back(result: true),
              child: const Text('确定'),
            ),
          ],
        ),
      ) ?? false;
      
      if (confirmed) {
        await _databaseService.deleteDatabase();
        await _databaseService.initDatabase();
        
        Get.snackbar(
          '成功', 
          '所有数据已清除', 
          snackPosition: SnackPosition.BOTTOM,
        );
      }
    } catch (e) {
      _errorMessage.value = '清除数据失败: ${e.toString()}';
      Get.snackbar('错误', '清除数据失败', snackPosition: SnackPosition.BOTTOM);
    } finally {
      _isLoading.value = false;
    }
  }

  /// 导出设置
  /// Export settings
  Future<Map<String, dynamic>> exportSettings() async {
    try {
      return await _settingsRepository.exportSettings();
    } catch (e) {
      _errorMessage.value = '导出设置失败: ${e.toString()}';
      return {};
    }
  }

  /// 导入设置
  /// Import settings
  Future<void> importSettings(Map<String, dynamic> settings) async {
    try {
      _isLoading.value = true;
      
      // 转换Map<String, dynamic>为Map<String, String>
      // Convert Map<String, dynamic> to Map<String, String>
      final Map<String, String> stringSettings = {};
      settings.forEach((key, value) {
        stringSettings[key] = value.toString();
      });
      
      await _settingsRepository.importSettings(stringSettings);
      await loadAllSettings();
      
      Get.snackbar('成功', '设置已导入', snackPosition: SnackPosition.BOTTOM);
    } catch (e) {
      _errorMessage.value = '导入设置失败: ${e.toString()}';
      Get.snackbar('错误', '导入设置失败', snackPosition: SnackPosition.BOTTOM);
    } finally {
      _isLoading.value = false;
    }
  }

  /// 获取应用信息
  /// Get app information
  Map<String, dynamic> getAppInfo() {
    return {
      'version': _appVersion.value,
      'database_path': _databasePath.value,
      'database_size': _databaseSize.value,
      'total_records': _totalRecords.value,
    };
  }

  /// 获取字体大小倍数
  /// Get font size multiplier
  double getFontSizeMultiplier() {
    switch (_fontSize.value) {
      case FontSize.small:
        return 0.9;
      case FontSize.medium:
        return 1.0;
      case FontSize.large:
        return 1.1;
      case FontSize.extraLarge:
        return 1.2;
    }
  }

  /// 获取提醒频率描述
  /// Get reminder frequency description
  String getReminderFrequencyDescription() {
    switch (_reminderFrequency.value) {
      case ReminderFrequency.never:
        return '从不';
      case ReminderFrequency.daily:
        return '每天';
      case ReminderFrequency.weekly:
        return '每周';
      case ReminderFrequency.monthly:
        return '每月';
    }
  }

  /// 清除错误信息
  /// Clear error message
  void clearError() {
    _errorMessage.value = '';
  }

  /// 刷新应用信息
  /// Refresh app info
  Future<void> refreshAppInfo() async {
    await loadAppInfo();
  }

  /// 发送反馈
  /// Send feedback
  Future<void> sendFeedback() async {
    // TODO: 实现发送反馈功能
    // Implement send feedback functionality
  }

  /// 评价应用
  /// Rate app
  Future<void> rateApp() async {
    // TODO: 实现应用评价功能
    // Implement rate app functionality
  }

  /// 设置应用锁定状态
  /// Set app lock enabled
  Future<void> setAppLockEnabled(bool enabled) async {
    _appLockEnabled.value = enabled;
    // TODO: 保存到数据库
  }

  /// 设置数据加密状态
  /// Set data encryption enabled
  Future<void> setDataEncryptionEnabled(bool enabled) async {
    _dataEncryptionEnabled.value = enabled;
    // TODO: 保存到数据库
  }

  /// 检查更新
  /// Check for updates
  Future<void> checkForUpdates() async {
    // TODO: 实现检查更新功能
    // Implement check for updates functionality
  }

  /// 显示用户协议
  /// Show user agreement
  Future<void> showUserAgreement() async {
    // TODO: 实现显示用户协议功能
    // Implement show user agreement functionality
  }

  /// 显示隐私政策
  /// Show privacy policy
  Future<void> showPrivacyPolicy() async {
    // TODO: 实现显示隐私政策功能
    // Implement show privacy policy functionality
  }

  /// 设置每日提醒状态
  /// Set daily reminder enabled
  Future<void> setDailyReminderEnabled(bool enabled) async {
    _dailyReminderEnabled.value = enabled;
    // TODO: 保存到数据库
  }

  /// 设置周末提醒状态
  /// Set weekend reminder enabled
  Future<void> setWeekendReminderEnabled(bool enabled) async {
    _weekendReminderEnabled.value = enabled;
    // TODO: 保存到数据库
  }

  /// 导出数据
  /// Export data
  Future<void> exportData() async {
    // TODO: 实现数据导出功能
    // Implement data export functionality
  }

  /// 导入数据
  /// Import data
  Future<void> importData() async {
    // TODO: 实现数据导入功能
    // Implement data import functionality
  }
}